package com.px.web.controller.system;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.px.common.annotation.Log;
import com.px.common.constant.UserConstants;
import com.px.common.core.controller.BaseController;
import com.px.common.core.domain.AjaxResult;
import com.px.common.core.domain.entity.SysUser;
import com.px.common.core.domain.model.LoginUser;
import com.px.common.enums.BusinessType;
import com.px.common.utils.CryptoUtil;
import com.px.common.utils.SecurityUtils;
import com.px.file.domain.SysFile;
import com.px.file.service.IFileService;
import com.px.framework.properties.ApplicationProperties;
import com.px.framework.web.service.TokenService;
import com.px.system.service.ISysUserService;
import com.px.common.constant.SysConstant;
import com.px.common.utils.PasswdValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author 品讯科技
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IFileService iFileService;

    /**
     * 获取个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        // LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return AjaxResult.success(ajax);
    }

    /**
     * 修改个人信息
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        if (StrUtil.isNotEmpty(user.getPhonenumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StrUtil.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.updateProfile(user) > 0) {
            // LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhonenumber(user.getPhonenumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 修改个人密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword, Integer encrypt) {
        Validator.validateNotEmpty(oldPassword, "旧密码不能为空");
        Validator.validateNotEmpty(newPassword, "新密码不能为空");
        if (!ObjectUtil.equal(encrypt, 0)) {
            String[] array = CryptoUtil.getCleartext(oldPassword, newPassword);
            oldPassword = array[0];
            newPassword = array[1];
        }
        int score = PasswdValidateUtil.getScore(newPassword);
        if (score < 60) {
            return AjaxResult.error("新密码强度太低");
        }
        // LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.updateProfilePwd(userName, newPassword, false) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 首次登录时强制要求修改密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateFirstPwd")
    public AjaxResult updateFirstPwd(String newPassword, Integer encrypt) {
        Validator.validateNotEmpty(newPassword, "新密码不能为空");
        if (!(ObjectUtil.equal(encrypt, 0) && StrUtil.equals(ApplicationProperties.profilesActive(), SysConstant.EnvDev))) {
            newPassword = CryptoUtil.getCleartext(newPassword);
        }
        int score = PasswdValidateUtil.getScore(newPassword);
        if (score < 60) {
            return AjaxResult.error("新密码强度太低");
        }
        // LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser.getUser().getPasswordNum() != null && loginUser.getUser().getPasswordNum() > 0) {
            return AjaxResult.error("密码已经修改过了");
        }
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.updateProfilePwd(userName, newPassword, true) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword).setPasswordNum(1);
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 修改个人头像
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                // LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
                LoginUser loginUser = SecurityUtils.getLoginUser();
                SysFile avatar = iFileService.uploadFile(file);
                // String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
                if (userService.updateProfileAvatar(loginUser.getUsername(), avatar.getUrl())) {
                    Map<String, Object> ajax = new HashMap<>();
                    ajax.put("imgUrl", avatar.getUrl());
                    // 更新缓存用户头像
                    loginUser.getUser().setAvatar(avatar.getUrl());
                    tokenService.setLoginUser(loginUser);
                    return AjaxResult.success(ajax);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

}
